<?php

function gen_page_top_right_str() {
  return isset($_SESSION["logged"]) ?
    $_SESSION['department_name'].' '.$_SESSION['name'].' | <a href="javascript:document.logout_form.submit();">注销</a>' :
    '';
}

function gen_page_top_left_str($title) {
  $new_hint = "&nbsp<span style='color:red'>New !</span>";
  if(!isset($_SESSION['logged'])) {
    $predefined_titles = array('Query'=>'index.php', 'Login'=>'login.php');
  } else if(isset($_SESSION['logged']) && is_senior_manager($_SESSION['user_id']) && !is_manager($_SESSION['user_id'])) {
    $predefined_titles = array('Query'=>'index.php', 'Report'=>'report.php');
  } else {
    $predefined_titles = array('Query'=>'index.php', 'Project'=>'project.php',
    'Task'=>'task.php', 'Wlog'=>'wlog.php', 'Summary'=>'wlog_summary.php',
	'Report'=>'report.php', 'Answer'=>'answer.php');
  }

  $title_elements = array();
  $predefined = false;

  while(list($predefined_title, $href) = each($predefined_titles)) {
    if($predefined_title != $title && $predefined_title != $title.$new_hint) {
      array_push($title_elements, "<a href=$href>$predefined_title</a>");
    } else {
      array_push($title_elements, $predefined_title);
      $predefined = true;
    }
  }

  if(!$predefined) {
    array_push($title_elements, $title);
  }

  return gen_sep_str($title_elements, ' | ');
}


function gen_header($title, $debug=0) {
  $rand_str = rand();
  $str = "
<html>

<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<link rel='stylesheet' href='./css/my.css?$rand_str'/>
<script type='text/javascript' src='./js/pub.js?$rand_str'></script>
<script type='text/javascript' src='./js/tablesort-min.js'></script>

<title>$title</title>
</head>

<body>

<form method='post' name='logout_form'><input type='hidden' name='logout'></input></form>";

  if(isset($_POST['logout'])) {
    $_SESSION = array();
    session_destroy();
    echo "<script>location.href='.'</script>";
  }

  $page_top_left = gen_page_top_left_str($title);
  if($debug) {
    $page_top_left .= "（调试中，如使用的是dev.qlog.me请转到qlog.me）";
  }

  $page_top_right = gen_page_top_right_str();

  $str .= "
<table class='page_top' width='100%'><tr>
<th align='left'>$page_top_left | <a href=http://forum.narisupport.us target=_blank><font color=#437dc0>讨论组</font></a></th>
<th align='right'>$page_top_right</th>
</tr></table>";

  return $str;
}

function gen_footer() {
  $str = "<div id='Footer'><footer><center>";


  $str .= "<p color=#f0>推荐使用google Chrome等支持HTML5新特性的浏览器。";
  if(isset($_SESSION['logged'])){
    $str .=  '纠错、补充内容或提意见：请<a href=mail.php>发邮件</a>。';
  }
  $str .= "</p>";


  $str .= '<p><a href=http://code.google.com/p/qpm>开发界面</a> ';
  if(isset($_SESSION['logged']) && isset($_SESSION['user_id']) && is_administrator($_SESSION['user_id'])) {
	$str .= ' <a href=http://qlog.me/cpanel>维护界面</a>';
  }
  $str .= '</p>';

  $str .= '</center></footer></div>';
  return $str;
}

function gen_select($name, $options, $preselection = "") {
  $str = "<select name=$name>";
  while(list($value, $display) = each($options)) {
    $str .= "<option value='$value'";
	if($value == $preselection) {
	  $str .= "selected ";
	}
	$str .=">$display</option>";
  }
  $str.='</select>';
  return $str;
}

function gen_twincol_table($name, $rows, $border=0) {
  $str = "<table name=$name border=$border>";
  while(list($left, $right) = each($rows)) {
    $str .= "<tr><td>$left</td><td>$right</td></tr>";
  }
  $str .= "</table>";
  return $str;
}

function gen_switch_divs($divs, $init_disp_div_name) {
  while(list($div_name, $div_content) = each($divs)) {
    $style_str = $init_disp_div_name != $div_name ? 'style="display:none"' : "";
    $str .= "<div name=$div_name id=$div_name $style_str>$div_content</div>";
  }
  return $str;
}

function gen_list($list_items, $list_type = "ol") { //another list type: "ul"
  $str = "<$list_type>";
  foreach($list_items as $item) {
    $str .= "<li>$item</li>";
  }
  $str .= "</$list_type>";
  return $str;
}

function gen_list_with_tip($list_items, $list_type = "ol") {   //another list type: "ul"
  $str = "<$list_type>";
  while(list($disp,$tip) = each($list_items)) {
    $str .= "<li class = 'tip'>$disp<span>".str_replace(chr(13), '<br/>', $tip)."</span></li>";
  }
  $str .= "</$list_type>";
  return $str;
}

function gen_twincol_page($title, $left_content, $right_content, $debug=1, $login_required=1) {
  $str = gen_header($title, $debug);
  if(1==$login_required && !isset($_SESSION['logged'])) {
    $str .= "<center><p>未登录</p></center>";
  } else {
    $str .= "<div id='content'>
  <div class='left'>".$left_content."</div>".
  "<div class='right'>".$right_content."</div>".
  "</div>";
  }
  $str .= gen_footer();
  return $str;
}

function gen_onecol_page($title, $content, $debug = 1, $login_required=1) {
  $str = gen_header($title, $debug);
  if(1==$login_required && !isset($_SESSION['logged'])) {
    $str .= "<center><p>未登录</p></center>";
  } else {
    $str .= "<center>$content</center>";
  }
  $str .= gen_footer();
  return $str;
}

function get_task_type_options() {
  $sql = "select id, name from task_type order by id";
  $rows = db_get($sql);

  foreach($rows as $row) {
    $options[$row['id']] = $row['name'];
  }
  return gen_select("type_id", $options);
}

function get_product_options() {
  $sql = "select id, name from product_info";
  $rows = db_get($sql);

  foreach($rows as $row) {
    $options[$row['id']] = $row['name'];
  }
  return gen_select("product_id", $options);
}

function gen_table($fields, $rows, $border=1, $fields_width) {
  $table_html = "<table border=$border><tr>";
  foreach($fields as $field=>$title) {
    $width_attr = '';
    if ($fields_width[$field]) {
      $width_attr = "width=$fields_width[$field]";
    }
    $table_html.="<th $width_attr>$title</th>";
  }
  $table_html.="</tr>";
  foreach($rows as $row) {
    $table_html .= "<tr>";
    foreach($fields as $field=>$title) {
      $table_html.= '<td>'.str_replace(chr(13), '<br/>', $row[$field]).'</td>';
    }
    $table_html .= "</tr>";
  }
  $table_html .= "</table>";
  return $table_html;
}

function gen_table_ext($fields, $rows, $border=1, $tableId, $tableClass, $tableFieldsAttr) {
  if (!$tableId || $tableId == '') {
    return '';
  }
  $table_order_mode_div_id = $tableId . '_order_mode';
  $table_html = "
  <div id='$table_order_mode_div_id'>当前排序方式：</div>
  <table id='$tableId' class='$tableClass' border='$border' width='100%'>
  <script type='text/javascript'>
  function sortCompleteCallback$tableId() {
    var trs = document.getElementById('$tableId').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    var cell;
    for(var i = 0, tr; tr = trs[i]; i++) {
      cell = tr.getElementsByTagName('td')[0];
      while(cell.firstChild) cell.removeChild(cell.firstChild);
      cell.appendChild(document.createTextNode(i + 1));
    }
    document.getElementById('$table_order_mode_div_id').innerHTML = '当前排序方式：' + fdTableSort.sortMode;
  }
  </script>
  <thead><tr>";
  foreach($fields as $field=>$title) {
    $id_attr = 'id='."'$tableId".'_'."$field'";
    $class_attr = '';
    $a_title_attr = '';

    $key = $field.'.class';
    if ($tableFieldsAttr[$key]) {
      $class_attr = "class='$tableFieldsAttr[$key]'";
    }
    $key = $field.'_a.title';
    if ($tableFieldsAttr[$key]) {
      $a_title_attr = "title='$tableFieldsAttr[$key]'";
    }

    if (stripos($class_attr, 'sortable') != false) {
      $table_html .= "<th $id_attr $class_attr><a href='#' class='fdTableSortTrigger' $a_title_attr>$title</a></th>";
    } else {
      $table_html .= "<th $id_attr $class_attr>$title</th>";
    }
  }
  $table_html .= "</tr></thead>
  <tbody>";
  foreach($rows as $row) {
    $table_html .= "<tr>";
    foreach($fields as $field=>$title) {
      $table_html.= "<td class='$field'>".str_replace(chr(13), '<br/>', $row[$field]).'</td>';
    }
    $table_html .= "</tr>";
  }
  $table_html .= "</tbody></table>";
  $table_html .= "<p class='table_footer_tip'><span>提示：</span>按住Shift键可多字段排序。</p>";
  return $table_html;
}

function gen_javascript_page($script) {
  $html_str = "<html><head><title>Javascript</title></head><body><script type='text/javascript'> $script </script></body></html>";
  return $html_str;
}

function gen_ticket_link($ticket_id) {
  $html_str = "";
  if($ticket_id > 0) {
    $html_str .= " <a href='http://scp.narisupport.me/tickets.php?id=$ticket_id' target=_blank>转到Ticket</a>";
  }
  return $html_str;
}

function get_assignto_select($user_id, $assigned_id = -1) {
  if(-1 == $assigned_id) {
    $assigned_id = $user_id;
  }
  $sql = "select to_id, name from assign_relation join user_info on to_id=id where from_id = ".$user_id;
  $rows = db_get($sql);
  $select_options = array();
  $select_options[$user_id] = '自己';
  foreach($rows as $row) {
    $select_options[$row['to_id']] = $row['name'];
  }

  return gen_select("assignto", $select_options, $assigned_id);
}

function str_replace_cr_lf_to_br($str) {
    $new_str = $str;
    $new_str = str_replace("\r\n", "<br>", $new_str);
    $new_str = str_replace("\r", "<br>", $new_str);
    $new_str = str_replace("\n", "<br>", $new_str);
    return $new_str;
}

function gen_outline_td($year, $week, $task_id, $outline_content, $user_id) {   
    $rele_plan_div_id = 'rele_plan_div_id_'.$task_id; 
    $outline_div_id = 'outline_div_id_'.$task_id;
    $outline_edit_div_id = 'outline_edit_div_id_'.$task_id;
    $outline_comment_div_id = 'outline_comment_div_id_'.$task_id;
    $outline_comment_edit_div_id = 'outline_comment_edit_div_id_'.$task_id;
    $outline_upd_btn_div_id = 'outline_upd_btn_div_id_'.$task_id;
    
    $outline_edit_textarea_id = 'outline_edit_textarea_id_'.$task_id;
    $outline_comment_edit_textarea_id = 'outline_comment_edit_textarea_id_'.$task_id;

    $outline_btn_if_display = (($_SESSION['user_id'] == $user_id || $_SESSION['is_manager']) ? '' : ' style=display:none ');
    $outline_comment_btn_if_display = ($_SESSION['is_manager'] ? '' : ' style=display:none ');
    
    $html = "<td onmouseover=switch_outline_td_disp('".$outline_upd_btn_div_id."','".$task_id."',1) onmouseout=switch_outline_td_disp('".$outline_upd_btn_div_id."','".$task_id."',0)>";
    $html .= "<div id='".$outline_upd_btn_div_id."' class='hide_outline_upd_btn_div'><button onclick=switch_the_disp('".$rele_plan_div_id."');>显示/隐藏计划及批注</button><button ".$outline_btn_if_display." onclick=switch_outline_td_disp('".$outline_upd_btn_div_id."','".$task_id."',0);switch_outline_td_disp('".$outline_edit_div_id."','".$task_id."',1);>编辑实施概要</button><button ".$outline_comment_btn_if_display." onclick=switch_outline_td_disp('".$outline_upd_btn_div_id."','".$task_id."',0);switch_outline_td_disp('".$outline_comment_edit_div_id."','".$task_id."',1);>编辑批注</button></div>";
    $html .= "<div id='".$outline_edit_div_id."' class='hide_outline_edit_div'>实施概要<button onclick=switch_outline_td_disp('".$outline_edit_div_id."','".$task_id."',0);>取消</button><button onclick=save_outline('".$year."','".$week."','".$task_id."','".$outline_edit_textarea_id."','".$outline_div_id."');>保存</button><textarea id='".$outline_edit_textarea_id."' class='outline_edit_textarea' rows='10'></textarea></div>";
    $html .= "<div id='".$outline_comment_edit_div_id."' class='hide_outline_comment_edit_div'>批注<button onclick=switch_outline_td_disp('".$outline_comment_edit_div_id."','".$task_id."',0);>取消</button><button onclick=save_outline_comment('".$year."','".$week."','".$task_id."','".$outline_comment_edit_textarea_id."','".$outline_comment_div_id."');>保存</button><textarea id='".$outline_comment_edit_textarea_id."' class='outline_comment_edit_textarea' rows='10'></textarea></div>";
    $rele_plan_content = '<div>无</div>';
    if ($outline_content['plan'] != '' || $outline_content['plan_comment'] != '') {
        $rele_plan_content = "<div>".str_replace_cr_lf_to_br($outline_content['plan'])."</div><div style='color:red'>".str_replace_cr_lf_to_br($outline_content['plan_comment'])."</div>";
    }
    $html .= "<div id='".$rele_plan_div_id."' class='rele_plan_div' style=display:none><span class='rele_plan_title'>计划及批注</span>".$rele_plan_content."</div>";
    $html .= "<div id='".$outline_div_id."' class='show_outline_div'>".str_replace_cr_lf_to_br($outline_content['outline'])."</div>";
    $html .= "<div id='".$outline_comment_div_id."' class='show_outline_comment_div'>".str_replace_cr_lf_to_br($outline_content['outline_comment'])."</div>";
    $html .= "</td>";
    
    return $html;
}

function gen_plan_td($year, $week, $task_id, $plan_content, $user_id) {    
    $plan_div_id = 'plan_div_id_'.$task_id;
    $plan_edit_div_id = 'plan_edit_div_id_'.$task_id;
    $plan_comment_div_id = 'plan_comment_div_id_'.$task_id;
    $plan_comment_edit_div_id = 'plan_comment_edit_div_id_'.$task_id;
    $plan_upd_btn_div_id = 'plan_upd_btn_div_id_'.$task_id;
    
    $plan_edit_textarea_id = 'plan_edit_textarea_id_'.$task_id;
    $plan_comment_edit_textarea_id = 'plan_comment_edit_textarea_id_'.$task_id;

    $plan_btn_if_display = (($_SESSION['user_id'] == $user_id || $_SESSION['is_manager']) ? '' : ' style=display:none ');
    $plan_comment_btn_if_display = ($_SESSION['is_manager'] ? '' : ' style=display:none ');
    
    $html = "<td onmouseover=switch_plan_td_disp('".$plan_upd_btn_div_id."','".$task_id."',1) onmouseout=switch_plan_td_disp('".$plan_upd_btn_div_id."','".$task_id."',0)>";
    $html .= "<div id='".$plan_upd_btn_div_id."' class='hide_plan_upd_btn_div'><button ".$plan_btn_if_display." onclick=switch_plan_td_disp('".$plan_upd_btn_div_id."','".$task_id."',0);switch_plan_td_disp('".$plan_edit_div_id."','".$task_id."',1);>编辑实施计划</button><button ".$plan_comment_btn_if_display." onclick=switch_plan_td_disp('".$plan_upd_btn_div_id."','".$task_id."',0);switch_plan_td_disp('".$plan_comment_edit_div_id."','".$task_id."',1);>编辑批注</button></div>";
    $html .= "<div id='".$plan_edit_div_id."' class='hide_plan_edit_div'>实施计划<button onclick=switch_plan_td_disp('".$plan_edit_div_id."','".$task_id."',0);>取消</button><button onclick=save_plan('".$year."','".$week."','".$task_id."','".$plan_edit_textarea_id."','".$plan_div_id."');>保存</button><textarea id='".$plan_edit_textarea_id."' class='plan_edit_textarea' rows='10'></textarea></div>";
    $html .= "<div id='".$plan_comment_edit_div_id."' class='hide_plan_comment_edit_div'>批注<button onclick=switch_plan_td_disp('".$plan_comment_edit_div_id."','".$task_id."',0);>取消</button><button onclick=save_plan_comment('".$year."','".$week."','".$task_id."','".$plan_comment_edit_textarea_id."','".$plan_comment_div_id."');>保存</button><textarea id='".$plan_comment_edit_textarea_id."' class='plan_comment_edit_textarea' rows='10'></textarea></div>";
    $html .= "<div id='".$plan_div_id."' class='show_plan_div'>".str_replace_cr_lf_to_br($plan_content['plan'])."</div>";
    $html .= "<div id='".$plan_comment_div_id."' class='show_plan_comment_div'>".str_replace_cr_lf_to_br($plan_content['plan_comment'])."</div>";
    $html .= "</td>";
    
    return $html;
}

function send_mail($subject, $message, $from_user_id, $to_user_id) {
    /* version: 20130803
    $from = "pslab@pslab.org";

    $sql = "select name, email from user_info where id = ".$from_user_id;
    $query = mysql_query($sql);
    $num = mysql_num_rows($query);
    if($num > 0) {
      $row = mysql_fetch_array($query);
      $cc = $row['name']."<".$row['email'].">";
    }
    
    $to = "";
    $sql = "select name, email from user_info where id = ".$to_user_id;
    $query = mysql_query($sql);
    $num = mysql_num_rows($query);
    if($num > 0) {
      $row = mysql_fetch_array($query);
      $to = $row['name']."<".$row['email'].">";
    }
    
    if ($to == "") {
        return;
    }
    
    //$headers = "From: $from "."\r\n"."Reply-To: $from". "\r\n";
    $headers = "From: $from"."\r\n";
    if ($to != $cc) {
        $headers .= "Cc: $cc"."\r\n";
    }
    $headers .= "Content-type: text/plain;charset=utf-8"."\r\n";

    mail($to,$subject,$message,$headers);
    */
    
    /* version: 20130808
    $from = "";
    $sql = "select name, email from user_info where id = ".$from_user_id;
    $query = mysql_query($sql);
    $num = mysql_num_rows($query);
    if($num > 0) {
      $row = mysql_fetch_array($query);
      $from = $row['name']."<".$row['email'].">";
    }
    if ($from == "") {
        return;
    }
    
    $to = "";
    if ($from_user_id == $to_user_id) {
        $to = $from;
    }
    else {
        $sql = "select name, email from user_info where id = ".$to_user_id;
        $query = mysql_query($sql);
        $num = mysql_num_rows($query);
        if($num > 0) {
          $row = mysql_fetch_array($query);
          $to = $row['name']."<".$row['email'].">";
        }
    }
    if ($to == "") {
        return;
    }
    
    $headers = "From: $from"."\r\n"."Reply-To: $from"."\r\n";
    $headers .= "Content-type: text/plain;charset=utf-8"."\r\n";

    mail($to,$subject,$message,$headers);
    */

    require_once("class.phpmailer.php");

    $automailer = array('name'=>'qlog-mailer', 'email'=>'qlogme@gmail.com', 'passwd'=>'naritech');
    $mail = new PHPMailer();
    $mail->IsSMTP();
    $mail->SMTPDebug  = 1;
    $mail->SMTPAuth   = true;
    $mail->Port       = 587;
    $mail->Host       = 'smtp.gmail.com';
    $mail->Username   = $automailer['email'];
    $mail->Password   = $automailer['passwd'];
    $mail->Timeout      = 15;
    $mail->SMTPSecure   = 'tls';

    $mail->From       = $automailer['email'];
    $mail->FromName   = $automailer['name'];
    
    if ($from_user_id != $to_user_id) {
        $sql = "select name, email from user_info where id = ".$from_user_id;
        $query = mysql_query($sql);
        $num = mysql_num_rows($query);
        if($num > 0) {
          $row = mysql_fetch_array($query);
          $mail->AddCC($row['email'], $row['name']);
          $mail->AddReplyTo($row['email'], $row['name']);
        }
        else {
            return;
        }
    }

    $sql = "select name, email from user_info where id = ".$to_user_id;
    $query = mysql_query($sql);
    $num = mysql_num_rows($query);
    if($num > 0) {
      $row = mysql_fetch_array($query);
      $mail->AddAddress($row['email'], $row['name']);
    }
    else {
        return;
    }
    
    $mail->Subject = $subject;
    $mail->Body = $message;
    
    $mail->CharSet = 'utf-8';
    $mail->ContentType = 'text/plain';

    try {
      if ( !$mail->Send() ) {
        $error = "Unable to send mail.<br />";
        throw new phpmailerAppException($error);
      }
    }
    catch (phpmailerAppException $e) {
      $errorMsg[] = $e->errorMessage();
    }
    
    if ( count($errorMsg) > 0 ) {
      foreach ($errorMsg as $key => $value) {
        $thisError = $key + 1;
        echo $thisError . ': ' . $value;
      }
    }
}

?>